<template>
  <div id="cart">
    <my-head title="购物车"></my-head>
    <div>
       <p id="warn" v-if="goods.length === 0">您还未添加商品</p>
       <div v-else>
         <van-swipe-cell v-for="(item, i) in goods" :key="i">
          <van-checkbox v-model="item.checked">
            <van-card
              :num="item.count"
              :price="item.price"
              :title="item.title"
              class="goods-card"
              :thumb="item.pic"
            />
            <template #right>
              <van-button square text="删除" type="danger" @click="delGood(i)" class="delete-button" />
            </template>
          </van-checkbox>
        </van-swipe-cell>
        <van-submit-bar :price="calcPrice" button-text="提交订单" @submit="onSubmit">
          <van-checkbox v-model="allCheck" @click="allClick">全选</van-checkbox>
        </van-submit-bar>
       </div>
       
    </div>
 </div> 
</template>

<script>
import myHead from '@/components/head'
export default {
  name: '',
  components: {
    myHead
  },
  data() { 
    return {
      goods: [],
      allCheck: false
    }
  },
  computed: {
    // 计算勾选中的商品总价
    calcPrice() {
      var sumPrice = 0
      this.goods.forEach((item) => {
        if(item.checked) {
          sumPrice += item.count*item.price*100
        }
      })
      return sumPrice
    }
  },
  created() {
    this.goods = JSON.parse(localStorage.getItem('list')) || []
  },
  methods:{
    delGood(i) {
      this.goods.splice(i, 1)
      localStorage.setItem('list', JSON.stringify(this.goods))
    },

    onSubmit() {

    },
    // 点击全选出发的事件
    allClick() {
      this.goods.forEach((item) => {
        item.checked = this.allCheck
      })
    }
  },

  watch: {
    goods: {
      // handler 数据发生变化时出发的函数
      handler() {
        this.allCheck = this.goods.every((item) => {
          return item.checked
        })
      },
      // 开启深度监听
      deep: true
    }
  }
 }
</script>

<style scoped>
#cart{
  height: 100vh;
  background: #f6f6f6;
}
  #warn{
    font-size: .3rem;
    line-height: 500px;
    color: #ccc;
    text-align: center;
  }

  >>>.goods-card {
    margin: 0;
    /* background-color: white; */
  }

  >>>.delete-button {
    height: 100%;
  }

  >>>.van-swipe-cell{
    margin-bottom: .4rem;
    background-color: #fff;
    padding: .4rem;
  }
  >>>.van-checkbox__label {
    width: 100%;
    margin-left: 0;
  }
  >>>.van-card{
    padding: 0;
  }
  >>>.van-card__content{
    background-color: #fff;
  }
</style>